<?php

namespace app\controller;

use app\BaseController;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Db;


class UserController extends BaseController
{
    public function info()
    {

        $user = Db::name('agent')->find($this->request->userId);
        return json(['code' => 200, 'msg' => 'success', 'data' => $user]);
    }


    public function wx()
    {

        $res = $this->get_access_token();
        $res = $this->get_wxa_code($res);

        return json(['code' => 200, 'msg' => 'success', 'data' => $res]);

    }


    //获取

    /**
     * @throws GuzzleException
     */
    protected function get_wx_openid($js_code)
    {
        $client = new Client();
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET') . '&js_code=' . $js_code . '&grant_type=authorization_code';
        $res = $client->request('GET', $url);
        $data = json_decode($res->getBody(), true);
        return $data['openid'] ?? null;
    }


    //获取Access token

    /**
     * @throws GuzzleException
     */
    protected function get_access_token()
    {
        $client = new Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET') . '&grant_type=client_credential';
        $res = $client->request('GET', $url);
        $data = json_decode($res->getBody(), true);
        return $data['access_token'] ?? null;
    }

    //获取小程序码
    protected function get_wxa_code($access_token)
    {
        $client = new Client();

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;

        $response = $client->post($url, [
            'json' => [
                'scene' => 'agent_id='.$this->request->userId,
                'env_version' => 'release',
                'width' => 280
            ],
            'headers' => [
                'Content-Type' => 'application/json'
            ]
        ]);

        $body = $response->getBody()->getContents();

        // 如果是图片（二维码）字节流，直接返回内容或保存
        $filename = runtime_path() . 'qrcode_' . time() . '.png';
        file_put_contents($filename, $body); // 保存为文件

        return $filename; // 或返回 base64，或直接返回内容 header 输出
    }


}
